@auth.requires_membership('admin')
def index():
    
    response.subtitle="%s -> %s" %(T('Admin'), T('Language'))
            
    if len(request.args)>0:            
        record = db.language(request.args[0])
        form=SQLFORM(db.language, record)
    else:
        form=SQLFORM(db.language)
            
    if form.accepts(request.vars, formname='form_language'):
        response.flash=T('Language saved')
        form=SQLFORM(db.language)
    elif form.errors:
        response.flash=T('Error')
                    
    languages= db().select(db.language.ALL)
                    
    return dict(languages=languages,  form=form)

@auth.requires_membership('admin')
def projects():
    
    response.subtitle="%s -> %s" %(T('Admin'), T('Project'))
        
    form=SQLFORM(db.project)
               
    if form.accepts(request.vars, formname='project_create'):
        response.flash=T('Project saved.')
    elif form.errors:
        response.flash=T('Error.')        
        
    #prjs= db().select(db.project.ALL)
    prjs=  db(db.project.source_language==db.language.id).select()
    languages_all= db().select(db.language.ALL, orderby=db.language.description
                               )    
    return dict(projects=prjs, subtitle=T('Projects'), languages=languages_all)

@auth.requires_membership('admin')
def project():
                
    prj_id=request.args[0]
    _project = db(db.project.id == prj_id).select().first()                    
    # Get all languages this project has.
                                        
    _projects=db(db.project_language.project == prj_id).select()
    _languages= db().select(db.language.ALL)
    
    # Prepare the form 
    #import pdb; pdb.set_trace()
    form=SQLFORM(db.project, _project)
                
    if form.accepts(request.vars, formname='project_update'):
        response.flash=T('Project saved.')        
        redirect(URL(r=request, f='projects'))         
    elif form.errors:        
        response.flash=T('Error.')
    
    
    response.subtitle="%s -> %s" %(T('Admin'), T('Project'))
        
    return dict(project=_project, project_and_languages=_projects, languages=_languages, form=form)
    
@auth.requires_membership('admin')    
def add_language():
              
    _project = db(db.project.id == request.vars.project).select().first()    
    _language=db(db.language.id == request.vars.language).select().first()            
    form=SQLFORM(db.project_language)
    
    # !! it's important do not use session in  form accept method and set the form name to None.
    
       
    if form.accepts(request.vars, formname=None):        
        return _languages_by_project(request.vars.project)
    elif form.errors:
        response.flash='Errors'
        return 'Error'
    else:                        
        return 'Fill in the form.'

@auth.requires_membership('admin')
def languages_by_project():
        
    prj_id=request.args[0]
            
    return _languages_by_project(prj_id)

    
def _languages_by_project(prj_id):
        
    _projects=db(db.project_language.project == prj_id).select()
        
    ret=''
    
    if _projects:            
        for i, row in enumerate(_projects):            
            ret+=TR(
                    TD(row.language.code), 
                    TD(row.language.description),
                    TD(
                       A(IMG(_src=URL( request.application , 'static/images', 'cancel.png')), _href='#', _onclick='delete_project_language(\'%s\')' %(row.id))                    
                    ), 
                    _class='even' if not i%2 else 'odd' ).xml()        
        
    return ret

@auth.requires_membership('admin')
def delete_language():
    
    lang_id=request.args[0]
    
    crud.delete(db.language, lang_id, URL('index'))

@auth.requires_membership('admin')    
def delete_project():
    
    prj_id=request.args[0]
    
    crud.delete(db.project, prj_id, URL('projects'))
    
@auth.requires_membership('admin')
def delete_project_language():
            
    id=request.vars.id
    
    _project_lang=db(db.project_language.id  == id).select().first()
    
    prj_id=_project_lang.project
                
    db(db.project_language.id == id).delete()
    
    return _languages_by_project(prj_id)

@auth.requires_membership('admin')
def users():    
    # read all users:
    
    # users=db().select(db.auth_user.ALL, db.auth_group.ALL, left=db.auth_membership.on((db.auth_user.id == db.auth_membership.user_id) & (db.auth_group.id == db.auth_membership.group_id)))
    
    users=db().select(db.auth_user.ALL,
        db.auth_group.ALL,
        left=[db.auth_membership.on(db.auth_user.id ==db.auth_membership.user_id),
        db.auth_group.on(db.auth_group.id ==db.auth_membership.group_id)])         

    user=None    
    is_admin=False
    
    if len(request.args)>0:
        user=db.auth_user(request.args[0])
        form=SQLFORM(db.auth_user, user)
        # check whether this user is admin:
        if db((db.auth_group.role == 'admin') & 
           (db.auth_group.id==db.auth_membership.group_id) & 
           (db.auth_membership.user_id==request.args[0])).select().first():
           is_admin=True

    else:        
        form=SQLFORM(db.auth_user)
        
                    
    if form.accepts(request.vars, formname='auth_user'):
        response.flash=T('User saved.')
        
        # Check whether the user has to be assigned with the role admin:        
        user_id=form.vars.id
                
        if request.vars.admin=='y':
            if not is_admin:
                # Insert a new record for the membership:
                role=db(db.auth_group.role == 'admin').select().first()
                
                db.auth_membership.insert(user_id=user_id, group_id=role.id)
        elif is_admin:
            # He don't want to be admin anymore:
            role=db(db.auth_group.role == 'admin').select().first()
                        
            # db.auth_membership(user_id=request.args[0], group_id=role.id).delete()
                        
            db((db.auth_membership.user_id == request.args[0]) & (db.auth_membership.group_id==role.id)).delete()
                        
                
        redirect(URL(r=request, f='users'))
                 
    elif form.errors:        
        response.flash=T('Error.')

    response.subtitle=T('Users')
    
    return dict(users=users, form=form, user=user, is_admin=is_admin)

@auth.requires_membership('admin')
def delete_user():
    
    usr_id=request.args[0]
    
    crud.delete(db.auth_user, usr_id, URL('users'))
